package com.company.algo.stack;

import java.util.LinkedList;
import java.util.Queue;

//使用队列实现栈
public class MyStack {
    private Queue<Integer> q;
    private int top_elem;
    public MyStack(){
        q = new LinkedList<>();
    }
    /** 添加元素到栈顶 */
    public void push(int x){
        q.offer(x);
        top_elem = x;
    }

    /** 删除栈顶的元素并返回
     * q  [(first)1,2,(last)3] -> [2,3,1]->poll->[2,3]
     * */
    public int pop(){
        int size = q.size();
        while (size>2){
            q.offer(q.poll());
            size--;
        }
        top_elem = q.peek();
        q.offer(q.poll());
        return q.poll();
    }

    /** 返回栈顶元素 */
    public int top(){
        return top_elem;
    }

    /** 判断栈是否为空 */
    public boolean empty(){
        return q.isEmpty();
    }
}
